#include <iostream>
#include <thread>

#include "cli.h"
#include "common.h"
#include "json.h"
#include "JsApp.h"
#include "server.h"
#include "VirtualScreen.h"
#include <csignal>


unsigned short port;
websocketpp::connection_hdl web_hdl;
server Simulator_Server;
bool m_send = false;
bool isChanged = false;
ProtocolMessage protocalMsg;
CliParam cliParam;
bool isAppRunning = true;

void sig_handler(int sig) {
    if(sig == SIGINT) {
        isAppRunning = false;
        on_stop(&Simulator_Server);
    }
}

int main(int argc, char *argv[]) {
    signal(SIGINT, sig_handler);

	// 解析命令行参数到 CliParam 封装类
    cliParam = GetOptLong(argc,argv);

    //判断jsBundle路径是否存在
    if(!cliParam.jsBundle.empty()) {
        if(access(cliParam.jsBundle.c_str(),0) == -1) {
            std::cout << "[Error]:Error jsBundle path!" << std::endl;
            return 0;
        }
        JsApp::GetInstance().SetJsAppPath(cliParam.jsBundle);
    }else {
        JsApp::GetInstance().SetJsAppPath(ApplicationPath() + "/entry/build/intermediates/res/debug/lite/assets/js/default");
    }

    //判断是否设置了websocket和http服务端口
    if(cliParam.webPort > 0){
        port = cliParam.webPort;
    }else {
        port = 3001;
    }

    std::string deviceStr;
    if (!ReadFileContent((ApplicationPath() + "/config/config.json").c_str(), std::ios_base::in, deviceStr)) {
        std::cerr <<"[ERROR]:Read device config error" << std::endl;
        return 0;
    }
    // 从json文件解析设备信息到 ProtocolMessage
    protocalMsg = ProtocolMessage::parseMessage(TrimUTF8BOM(deviceStr));

    if(!cliParam.projectName.empty()) {
        JsApp::GetInstance().SetUuid(cliParam.projectName);
    }else {
        JsApp::GetInstance().SetUuid("com.shenhonghui.previewer");
    }

    JsApp::GetInstance().SetJSHeapSize(4096 * 4096);
    if(JsApp::GetInstance().Start()) {
        try {
            on_run(&Simulator_Server, port);
        }
        catch (websocketpp::exception const& e) {
            std::cout << e.what() << std::endl;
        }
        catch (const std::exception& e) {
            std::cout << e.what() << std::endl;
        }
        catch (...) {
            std::cout << "other exception" << std::endl;
        }
    } else {
        std::cout << "App failed to start !" << std::endl;
    }

    return 0;
}
